<?php

// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 应用公共文件
// 获取资源文件




/**
 * @title 生成参数列表,以数组形式返回
 */
function _sys_parm_array($tag = '') {
    $param = array();
    $array = explode(';', $tag);
    foreach ($array as $v) {
        $v = trim($v);
        if (!empty($v)) {
            list($key, $val) = explode(':', $v);
            $param[trim($key)] = trim($val);
        }
    }
    return $param;
}

/**
 * @title 获取单条文章
 * @param type $tag
 * @param type $where
 * @return type@
 */
function details_article($tag, $where = []) {
    $tag = _sys_parm_array($tag);
    $field = !empty($tag['field']) ? $tag['field'] : '*';
    $limit = !empty($tag['limit']) ? $tag['limit'] : '';
    $order = !empty($tag['order']) ? $tag['order'] : 'id';
    if (!is_array($where)) {
        $where = [];
    }
    $one = \think\Db::name("article")->alias("a")->field($field)->where($where)->order($order)->limit($limit)->find();
    return $one;
}

/**
 * 8 查询文章列表（不做分页）
 * @param string $tag  查询标签，以字符串方式传入,例："cid:1,2;field:post_title,post_content;limit:0,8;order:post_date desc,listorder desc;where:id>0;"<br>
 *  ids:调用指定id的一个或多个数据,如 1,2,3<br>
 * 	cid:数据所在分类,可调出一个或多个分类数据,如 1,2,3 默认值为全部,在当前分类为:'.$cid.'<br>
 * 	field:调用post指定字段,如(id,post_title...) 默认全部<br>
 * 	limit:数据条数,默认值为10,可以指定从第几条开始,如3,8(表示共调用8条,从第3条开始)<br>
 * 	order:排序方式，如：post_date desc<br>
 * 	where:查询条件，字符串形式，和sql语句一样
 * @param array $where 查询条件，（暂只支持数组），格式和thinkphp where方法一样；
 */
function lists_article($tag, $where = []) {

    $tag = _sys_parm_array($tag);
    $field = !empty($tag['field']) ? $tag['field'] : '*';
    $limit = !empty($tag['limit']) ? $tag['limit'] : '';
    $order = !empty($tag['order']) ? $tag['order'] : 'id';
    if (!is_array($where)) {
        $where = [];
    }
    //$where['delete_time'] = ['NOT NULL'];

    $lists = \think\Db::name("article")->alias("a")->field($field)->where($where)->order($order)->limit($limit)->select();
    return $lists;
}







function getSign($row) {
    $t = $row + 1;
    if ($t > date('d')) {
        $td = "<td style='background-color:lemonchiffon' valign='top'>
<div align='right' valign='top'><span style='position:relative;right:20px;'>" . $t . "</span>
</div><div align='left'> </div><div align='left'> </div></td>";
    } else {
        if (strlen($t) == 1) {
            $day = "0" . $t;
        } else {
            $day = $t;
        }
        $t2 = strtotime(date("Y-m-" . $day . ""));
        $info = db("member_sign")->field("id")->where("create_time = " . $t2 . " AND status = 0 AND uid = " . MID . "")->find();

        if ($info) {
            $td = "<td style='background-color:navajowhite;navajowhite ;'>
<div align='right' valign='top'><span style='position:relative;right:20px;'>" . $t . "</span>
</div><div align='left'>
<i class='small material-icons' style='position:relative;left:10px;color:#00BB00'>check</i> 已签到
</div></td>";
        } else {
            if ($t == date('d')) {
                $td = "<td  class='today'>
<div align='right' valign='top'><span style='position:relative;right:20px;'>" . $t . "</span></div>
<div align='center'><a style='cursor:pointer;color:#ffffff;' >签到</a></div></td>";
            } else {
                $td = "<td style='background-color:#DCDCDC;'>
<div align='right' valign='top'><span style='position:relative;right:20px;'>" . $t . "</span>
</div><div align='left'style='height:47px'>
</div></td>";
            }
        }
    }
    return $td;
}


/**
 * 参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
 * @param type $url
 * @param type $post
 * @param type $cookie
 * @param type $returnCookie
 * @return type
 */
function curl_request($url, $post = '', $cookie = '', $returnCookie = 0) {

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    if (isset($_SERVER['HTTP_REFERER']))
        curl_setopt($curl, CURLOPT_REFERER, $_SERVER['HTTP_REFERER']);

    if ($post) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    if ($cookie) {
        curl_setopt($curl, CURLOPT_COOKIE, $cookie);
    }
    curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        return curl_error($curl);
    }
    curl_close($curl);
    if ($returnCookie) {
        list($header, $body) = explode("\r\n\r\n", $data, 2);
        preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
        $info['cookie'] = substr($matches[1][0], 1);
        $info['content'] = $body;
        return $info;
    } else {
        return $data;
    }
}

/**
 * @title 时间格式化
 */
function datatime($val) {
    return date('Y-m-d H:i:s', $val);
}

/**
 * @title 1\生成前台面包屑
 * 基于nav的path信息
 */
function nav_breadcrumb($nav_id, $header = '当前位置：', $footer = '', $divide = ' > ') {

    $this_array = array();

    //通过category获取到的ID在 nav里面反查navid
    $result = \think\Db::name('nav')->where('id', $nav_id)->find();

    if ($result) {


        //通过navid在nav表面的去查找path信息，然后根据path里的路径去生成bread
        //print_r($result);exit;			

        $path_arr = explode('-', $result['path']);
        foreach ($path_arr as $key => $val) {


            if ($val == 0) {
                continue;
            }

            $result_parent = \think\Db::name('nav')->where('id', $val)->find();
            if ($result_parent) {
                $this_array[] = [
                    'title' => $result_parent['name'], 'href' => $result_parent['href']
                ];
            }
        }
    }


    $temp_str = '';


    echo $header . '<a href="' . config('site_url') . '">首页</a> ';
    foreach ($this_array as $key => $val) {


        $val['href'] = my_url(strtolower($val['href']));

        $temp_str .= $divide . ' <a href="' . $val['href'] . '">' . $val['title'] . '</a>  ';
        //echo $divide.' <a href="'.UU($val['href']).'">'.$val['title'].'</a>  ';
    }
    echo $temp_str;


    if (!empty($footer)) {
        echo $divide . $footer;
    }
}

/**
 * @title 为了兼容tp3.2写的一个获取配置的函数
 */
function get_config($key) {

    $value = \think\Db::name("config")->where('name', $key)->value('value');
    return $value;
}



/**
 * @title 获取上架商品列表
 * @param type $tag
 * @param type $where
 * @return type
 */
function lists_goods($tag, $where = []) {
    $tag = _sys_parm_array($tag);
    $field = !empty($tag['field']) ? $tag['field'] : '*';
    $limit = !empty($tag['limit']) ? $tag['limit'] : '';
    $order = !empty($tag['order']) ? $tag['order'] : 'id';
    if (!is_array($where)) {
        $where = [];
    }
    // $where['status'] = ['=', 1];
    $lists = \think\Db::name("goods")->alias("a")->field($field)->where($where)->order($order)->limit($limit)->select();
    return $lists;
}

/**
 * @title 获取单条导航
 * @param type $tag
 * @param type $where
 * @return type@
 */
function details_nav($tag, $where = []) {
    $tag = _sys_parm_array($tag);
    $field = !empty($tag['field']) ? $tag['field'] : '*';
    $limit = !empty($tag['limit']) ? $tag['limit'] : '';
    $order = !empty($tag['order']) ? $tag['order'] : 'id';
    if (!is_array($where)) {
        $where = [];
    }
    $one = \think\Db::name("nav")->alias("a")->field($field)->where($where)->order($order)->limit($limit)->find();
    return $one;
}

/**
 * @title 分类的导航
 * @param type $cid
 * @param type $pid nav表中再次根据pid过滤
 */
function get_nav($cid = 0, $pid = 0) {

    $map = null;
    // $map['pid'] = ['=', $pid];
    $map['cid'] = $cid;
    $result = db("nav")->where($map)->order("listorder ASC, id asc")->select();


    // dd($result);

    $lists = [];
    if ($result) {
        foreach ($result as $key => $value) {
            // 处理href
            $result[$key]['href'] = my_url($result[$key]['href']);
        }

        $lists = node_merge($result, null, $pid);
    }

    return $lists;
}

/**
 * @title 获取子导航
 */
function sub_nav($pid) {

    $map['pid'] = ['=', $pid];
    // $map['status'] = ['>', 0];
    //$map['cid'] = $cid;
    $lists = \think\Db::name("nav")->where($map)->order("listorder ASC")->select();
    return $lists;
}

/**
 * @title 获取文章分类列表
 */
function lists_article_cat($tag, $where = []) {

    $tag = _sys_parm_array($tag);
    $field = !empty($tag['field']) ? $tag['field'] : '*';
    $limit = !empty($tag['limit']) ? $tag['limit'] : '';
    $order = !empty($tag['order']) ? $tag['order'] : 'id';
    if (!is_array($where)) {
        $where = [];
    }

    $result = \think\Db::name("article_cat")->field($field)->where($where)->order($order)->limit($limit)->select();

    foreach ($result as $key => $value) {

        //加载分类的文章数量
        $map['cid'] = $value['id'];
        $map['delete_time'] = NULL;
        $result[$key]['count'] = \think\Db::name("article")->where($map)->order("listorder ASC, id asc")->count();
    }
    return $result;
}

/**
 * @title 获取商品分类列表
 */
function lists_goods_cat($tag, $where = []) {

    $tag = _sys_parm_array($tag);
    $field = !empty($tag['field']) ? $tag['field'] : '*';
    $limit = !empty($tag['limit']) ? $tag['limit'] : '';
    $order = !empty($tag['order']) ? $tag['order'] : 'id';
    if (!is_array($where)) {
        $where = [];
    }

    $result = \think\Db::name("goods_cat")->field($field)->where($where)->order($order)->limit($limit)->select();

    foreach ($result as $key => $value) {

        //加载分类的数量
        $map['cid'] = $value['id'];
        $map['delete_time'] = NULL;
        $result[$key]['count'] = \think\Db::name("goods")->where($map)->order("listorder ASC, id asc")->count();
    }
    return $result;
}
